import { domain } from '@/little/config';

export function cdn(uri = null, mode = 0, defaultimg = null, dMode = 1) {
    if (isUrl(uri)) {
        return uri;
    }
    if (!uri || uri.lenght <= 1) {
        uri = defaultimg;
        mode = dMode;
    }
    switch (mode) {
        case 0:
            uri += '/static/';
            break;
        case 1:
            uri = domain.cdn + uri;
            break;
        case 2:
            uri = domain.remote + uri;
            break;
        case 3:
            uri = domain.online + uri;
            break;
        default:
            break;
    }
    return uri;
}

export function percentage(num, total) {
    if (num == 0 || total == 0) {
        return 0;
    }
    return Math.round((Math.round(total - num) / total) * 10000) / 100.0; // 小数点后两位百分比
}

export function isUrl(str) {
    return /^(http|https):\/\/[^\s]+$/.test(str);
}
export function isMobile(str) {
    return /^1[3456789]\d{9}$/.test(str);
}

export function isIdCard(str) {
    return /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(str);
}
export const sleep = (time) => {
    return new Promise((resolve) => setTimeout(resolve, time));
};

//  去重
export const unique = (a) => {
    return Array.from(new Set(a));
};
// 并集 去重 合并
export const union = (a, b) => {
    const c = new Set(a);
    const d = new Set(b);
    return unique(new Set([...c, ...d]));
};

// 交集
export const intersect = (a, b) => {
    const c = new Set(a);
    const d = new Set(b);
    return new Set([...c].filter((x) => d.has(x)));
};
// 差集
export const difference = (a, b) => {
    const c = new Set(a);
    const d = new Set(b);
    return new Set([...c].filter((x) => !d.has(x)));
};
// 打乱数组
export const randomArray = (array = []) => {
    // 原理是sort排序,Math.random()产生0<= x < 1之间的数,会导致x-0.05大于或者小于0
    return array.sort(() => Math.random() - 0.5);
};
// 数组查找
export const inArray = (search = '', array = []) => {
    return array.some((item) => item == search);
};
// 脱敏
export const desensitize = (str, args = {
    before: 3,
    after:4
}) => {
    if (str == undefined) return ''
    const regex = new RegExp(`(\\d{${args.before}})\\d*(\\d{${args.after}})`)
    return String(str).replace(regex, '$1****$2');
}
